﻿using HandyControl.Controls;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml;

namespace TransformerManager.WPF.Common.Views
{
    /// <summary>
    /// Interaction logic for AboutDialog
    /// </summary>
    public partial class AboutDialog : UserControl
    {
        const string xmlFilePath = @"VersionInfo.xml";
        public AboutDialog()
        {
            InitializeComponent();

            LoadVersionInfo();
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string edgeKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\msedge.exe";
                string chromKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe";
                string openKey = string.Empty;
                var result = HandyControl.Controls.MessageBox.Show(
                        "是否使用Chrome浏览器打开? 否则软件将尝试使用Edge浏览器打开。",
                        "询问",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    openKey = chromKey;
                }
                else
                {
                    openKey = edgeKey;
                }

                var appPath = Registry.LocalMachine.OpenSubKey(openKey).GetValue("").ToString();
                if (appPath != null)
                {
                    Process.Start(appPath, ((Hyperlink)sender).NavigateUri.ToString());
                }
            }
            catch (System.ComponentModel.Win32Exception noBrowser)
            {
                if (noBrowser.ErrorCode == -2147467259)
                    HandyControl.Controls.MessageBox.Show(
                        noBrowser.Message,
                        "失败",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
            }
            catch (System.Exception other)
            {
                HandyControl.Controls.MessageBox.Show(
                    other.Message,
                    "失败",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }

        }

        private void LoadVersionInfo()
        {
            try
            {
                string path = Directory.GetCurrentDirectory().ToString();
                string fileName = $"{path}\\XML\\{xmlFilePath}";
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(fileName);

                XmlNodeList topNode = xmldoc.DocumentElement.ChildNodes;
                foreach (XmlElement element in topNode)
                {
                    if (element.Name.ToLower() == "applicationinfo")
                    {
                        var version = element.GetElementsByTagName("ProductVersion")[0].InnerText;
                        var tb = this.FindName("TbNewestVersion") as TextBlock;
                        tb.Text = $"{version}-Release";
                    }

                    if (element.Name.ToLower() == "updateinfos")
                    {
                        XmlNodeList nodes = element.ChildNodes;
                        foreach (XmlElement node in nodes)
                        {
                            var version = node.GetAttribute("version").ToString();
                            var date = node.GetAttribute("date").ToString();
                            var feats = node.GetElementsByTagName("Features")[0];
                            var rtb = this.FindName("RtbUpdateInfo") as RichTextBox;

                            Paragraph paraVersion = new Paragraph();
                            Paragraph paraContent = new Paragraph();
                            Paragraph paraSplitLine = new Paragraph();

                            paraVersion.FontSize = 20;
                            paraVersion.Inlines.Add($"version: {version}-release date: {date} \n");

                            paraContent.FontSize = 16;
                            paraContent.Foreground = new SolidColorBrush(Colors.Gray);

                            foreach (XmlElement feat in feats)
                            {

                                string text = $"* {feat.InnerText}\n";
                                paraContent.Inlines.Add(new Run(text));

                            }

                            rtb.Document.Blocks.Add(paraVersion);
                            rtb.Document.Blocks.Add(paraContent);
                            paraSplitLine.Inlines.Add("_____________________________" +
                                "___________________________________________________");
                            rtb.Document.Blocks.Add(paraSplitLine);
                        }
                    }

                    if (element.Name.ToLower() == "opensourcereference")
                    {
                        XmlNodeList ossNodes = element.ChildNodes;
                        foreach (XmlElement ossNode in ossNodes)
                        {
                            var packageNodes = ossNode.ChildNodes;
                            var rtb = this.FindName("RtbOSSInfo") as RichTextBox;

                            var appName = ossNode.GetAttribute("AppName").ToString();
                            Paragraph paraAppName = new Paragraph();
                            Paragraph paraSplitLine = new Paragraph();
                            paraAppName.FontSize = 20;
                            paraAppName.Inlines.Add(new Run(appName));
                            rtb.Document.Blocks.Add(paraAppName);
                            foreach (XmlElement packageNode in packageNodes)
                            {
                                Paragraph paraPackageInfo = new Paragraph();
                                paraPackageInfo.FontSize = 16;

                                string license = packageNode.GetAttribute("license").ToString();
                                string version = packageNode.GetAttribute("version").ToString();
                                string packageName = packageNode.InnerText;
                                string text = $"License : {license} | Version : {version}\n" +
                                    $"Package : {packageNode.InnerText}\n";
                                paraPackageInfo.Inlines.Add(new Run(text));

                                rtb.Document.Blocks.Add(paraPackageInfo);
                            }
                            paraSplitLine.Inlines.Add("_____________________________" +
                                    "___________________________________________________");
                            rtb.Document.Blocks.Add(paraSplitLine);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                HandyControl.Controls.MessageBox.Show(
                    "无法加载软件信息。\n" +
                    $"错误信息:{e.Message}",
                    "失败",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }
    }
}
